package com.gf.framework.mysql.service;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gf.framework.common.utils.SpringContextUtil;
import com.gf.framework.idgenetor.config.IdGenetorConfig;
import com.gf.framework.idgenetor.config.SnowFlakeIdGentetor;
import com.gf.framework.mysql.entity.BaseEntity;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * @author gaofei
 * @date 2022/6/12 14:38
 */
public abstract class SnowServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> extends ServiceImpl<M, T>
        implements SmartInitializingSingleton, ISnowService<T>{
    protected SnowFlakeIdGentetor snowFlakeIdGentetor;

    @Override
    public boolean save(T entity) {
        if (!autoId()) {
            entity.setId(nextId());
        }
        return super.save(entity);
    }

    @Override
    public boolean saveOrUpdate(T entity) {
        if (!autoId() && entity.getId() != null) {
            entity.setId(nextId());
        }
        return super.saveOrUpdate(entity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveBatch(Collection<T> entityList) {
        if (!autoId()) {
            for (T entity : entityList )
                entity.setId(nextId());
        }
        return super.saveBatch(entityList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) {
        if (!autoId()) {
            for (T entity : entityList )
                entity.setId(nextId());
        }
        return super.saveOrUpdateBatch(entityList, batchSize);
    }

    @Override
    public void afterSingletonsInstantiated() {
        snowFlakeIdGentetor = SpringContextUtil.getBean(IdGenetorConfig.class).
                getSnowFlakeIdGentetorByTableName(TableInfoHelper.getTableInfo(getEntityClass()).
                        getTableName());
    }

    @Override
    public Long nextId() {
        return snowFlakeIdGentetor.nextId();
    }
}
